<template>
    <div>
        <el-card style="width:50%">
            <el-form ref="formRef" :model="user" :rules="rules" label-width="80px" style="padding-right: 30px">
                <el-form-item label="原密码" prop="pwd">
                    <el-input show-password v-model="user.pwd" id="pwd"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPwd">
                    <el-input show-password v-model="user.newPwd" id="newPwd"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="dPwd">
                    <el-input show-password v-model="user.dPwd" id="dPwd"></el-input>
                </el-form-item>
                <div style="text-align:center">
                    <el-button type="primary" @click="update">确认修改</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default{
    name:"Password",
    data(){
        const validatePassword =(rule,value,callback)=>{
            if(value===''){
                callback(new Error('请确认密码'))
            }else if(value!==this.user.newPwd){
                callback(new Error('确认密码错误'))
            }else{
                callback()
            }
        }

        return {
            user:JSON.parse(localStorage.getItem('honey-user') || '{}'),
            rules:{
                pwd: [
                    { required: true, message:'请输入原密码', trigger: 'blur' },
                ],
                newPwd: [
                    { required: true, message:'请输入新密码', trigger: 'blur' },
                ],
                dPwd: [
                    { validator:validatePassword, required: true,trigger: 'blur' },
                ],
            },
        }
    },
    created(){

    },
    methods:{
        update(){
            this.$refs.formRef.validate((valid)=>{
                if(valid){
                    this.user.pwd=this.user.newPwd
                    //保存当前用户信息到数据库
                    this.$request.put('/user/update',this.user).then(res=>{
                        if(res.code==='200'){
                            this.$message.success('保存成功')
                            this.$router.push('/login')
                        }else{
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        }
    }
}
</script>

<style scoped>
.el-form-item__label{
    font-weight:bold;
}
</style>